const express = require("express");
const { getUnix, multer } = require("../../model/tools");
const FocusModel = require("../../model/FocusModel")
const fs = require('fs');

var router = express.Router();
router.get("/", async (req, res) => {

    let result = await FocusModel.find({})

    res.render("admin/focus/index.html", {
        list: result
    })
})

router.get("/add", async (req, res) => {
    res.render("admin/focus/add.html")
})

router.post("/doAdd", multer().single('focus_img'), async (req, res) => {

    // static\\upload\\****\\****.jpg

    // req.file.path.split('\\').slice(1).join('/')

    let focus_img = req.file && req.file.path.substr(7)

    let focusImgObj = { "focus_img": focus_img }

    let result = new FocusModel(Object.assign(req.body, focusImgObj))

    await result.save()

    res.redirect(`/${req.app.locals.adminPath}/focus`)
})

router.get("/edit", async (req, res) => {

    let id = req.query.id

    let result = await FocusModel.find({ "_id": id })

    res.render("admin/focus/edit.html", {
        list: result[0]
    })
})

router.post("/doEdit", multer().single('focus_img'), async (req, res) => {
    try {
        let id = req.body.id

        if (req.file) {     // 进行图片修改
            // 修改前需要删除旧文件
            let resultList = await FocusModel.find({ "_id": id })

            if (resultList[0].focus_img) {
                fs.unlink("static/" + resultList[0].focus_img, (err) => {
                    console.log(err);
                })
            }

            let focus_img = req.file && req.file.path.substr(7)

            await FocusModel.updateOne({ "_id": id }, Object.assign(req.body, { focus_img }))

        } else {    // 不进行图片修改
            await FocusModel.updateOne({ "_id": id }, req.body)
        }
        res.render('admin/public/success', {
            "message": '修改成功',
            "redirectUrl": `/${req.app.locals.adminPath}/focus`
        })
    } catch (error) {
        res.render('admin/public/error', {
            "message": '修改轮播图数据失败',
            "redirectUrl": `/${req.app.locals.adminPath}/focus/edit?id=${id}`
        })
    }
})

router.get("/delete", async (req, res) => {
    let id = req.query.id

    let resultList = await FocusModel.find({ "_id": id })
    let delResult = await FocusModel.deleteOne({ "_id": id })

    // 顺带删除upload文件夹的文件
    if (delResult.ok === 1 && delResult.n === 1) {
        if (resultList[0].focus_img) {
            fs.unlink("static/" + resultList[0].focus_img, (err) => {
                console.log(err);
            })
        }
    }

    if (delResult) {
        res.render('admin/public/success', {
            "message": '删除轮播图数据成功',
            "redirectUrl": `/${req.app.locals.adminPath}/focus`
        })
    }
})

module.exports = router